package com.grape.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grape.vo.RoleMenuVO;
import com.grape.domain.SysRoleMenu;
import com.grape.mapper.SysRoleMenuMapper;
import com.grape.service.ISysRoleMenuService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 角色菜单中间表 服务实现类
 *
 * @author  putao
 * @email   2628279194@qq.com
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    private static final Logger logger = LoggerFactory.getLogger(SysRoleMenuServiceImpl.class);

    private final SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 根据id查询详情
     * @param id    角色菜单ID
     * @return      角色菜单中间表对象
     */
    @Override
    public SysRoleMenu detail(String id) {
        return this.getById(id);
    }

    /**
     * 修改角色的权限
     * @param roleMenuVo  角色和菜单数据
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void updateRoleMenuList(RoleMenuVO roleMenuVo) {
        int count = sysRoleMenuMapper.delete(new QueryWrapper<SysRoleMenu>().eq("role_id", roleMenuVo.getRoleId()));
        logger.info("执行删除角色权限数据操作，共删除: {} 条数据", count);
        List<String> menuIdList = roleMenuVo.getMenuIdList();
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        for (String menuId : menuIdList) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(IdUtil.getSnowflake(31, 31).nextIdStr());
            sysRoleMenu.setRoleId(roleMenuVo.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            roleMenuList.add(sysRoleMenu);
        }
        this.saveBatch(roleMenuList);
    }
}
